<template>
  <div class="makeorderbox">
    <!-- 录入订单 -->
    <div class="modalboxs">
      <a-spin :spinning="orderisLoading">
        <template>

          <div class="orderbox">
            <div class="orderitem">
              <p>顾客姓名：</p>
              <a-select v-model="customer" showSearch mode="combobox" style="width: 100%" placeholder="请选择客户"
                @change="handleChangecustomer">
                <a-select-option v-for="i in customerlist" :key="i.long_info">
                  {{ i.long_info }}
                </a-select-option>
              </a-select>
            </div>
          </div>
          <div class="orderboxaddress">
            <div class="orderitem">
              <p>配送地址：</p>
              <a-input placeholder="请输入你要查找的关键词" @input="onInput" id="my-panel" v-model="userInput">
              </a-input>
              <div v-if="showSuggestions" class="autocomplete-results">
                <div v-for="(suggestion, index) in suggestions" :key="index" @click="selectSuggestion(suggestion)">
                  <p style="font-size: 15px; font-weight: bold;">{{ suggestion.name }}</p>
                  <p v-if="suggestion.address != ''">{{ suggestion.address }}</p>
                </div>
              </div>
            </div>
            <!-- <div class="">
              <p>坐标：{{ lng }}-{{ lat }}</p>
            </div> -->
          </div>
          <div class="orderbox">
            <div class="orderitem">
              <p>顾客电话：</p>
              <!-- <a-input placeholder="请输入手机号" v-model="phone" /> -->
              <a-select v-model="phone" showSearch mode="combobox" style="width: 100%" placeholder="请选择"
                @change="handleChangephone">
                <a-select-option v-for="i in customerphonelist" :key="i">
                  {{ i }}
                </a-select-option>
              </a-select>
            </div>
          </div>
          <div class="orderbox">
            <div class="orderitem">
              <p>详细地址：</p>
              <a-input placeholder="请输入详细地址" v-model="detailaddress">
              </a-input>
            </div>
          </div>
          <div class="orderbox">
            <!-- <div class="">
              <p>详细地址：</p>
              <div id="container"></div>
            </div> -->
            <div id="container"></div>

          </div>


          <div class="orderbox">
            <div class="orderitem" style="width: 100%">
              <p>发送门店：</p>
              <a-select style="width: 100%" placeholder="请选择门店" @change="handleChangeshop">
                <a-select-option v-for="i in shopListTreeData" :key="i.store_id">
                  {{ i.name }}
                </a-select-option>
              </a-select>
            </div>
            <div style="flex-shrink: 0;">
              <span>活跃：{{ storecount.run_total }}人</span>
              <span class="ml-10 mr-10">待接单：{{ storecount.wait_total }}单</span>
              <span>配送中：{{ storecount.delivery_total }}单</span>
            </div>
          </div>
          <div class="orderbox">
            <div class="orderitem">
              <p>配送时间：</p>
              <a-date-picker style="width: 100%" show-time placeholder="选择时间 " v-model="pre_times"
                format="YYYY-MM-DD HH:mm" @change="onOk" />
            </div>
          </div>
          <div class="orderbox">
            <div class="orderitem">
              <p>本单备注：</p>
              <a-textarea placeholder="请输入买家备注" v-model="buyer_remark" />
            </div>
          </div>
          <div class="orderbox">
            <div class="orderitem" style="width:500px">
              <p>商品名称：</p>
              <a-button type="primary" @click="opengoodspop">选择商品</a-button>
              <div class="heji">
                合计：
                <span style=" color: lightcoral; font-weight:bold; font-size:22px">￥{{ allprice }}</span>
              </div>
              <div class="heji">
                实付：
                <span style=" color: lightcoral; font-weight:bold; font-size:22px">￥{{ (allprice -
                  coupon_money).toFixed(2) }}</span>
              </div>
            </div>
          </div>
          <div class="goodscontent">
            <div class="goodsitembox" v-for="(i, index) in carlist" :key="index">
              <div class="goodsitembox_left">
                <img class="mr-10" :src="i.image" alt="">
                <div class="goodsitembox_left_text">
                  <p class="oneline-hide" style="width:80px">
                    <a-popover>
                      <template slot="content">
                        {{ i.name }}
                      </template>
                      {{ i.name }}
                    </a-popover>
                  </p>
                  <p style="color: lightcoral;">￥{{ i.price }}</p>
                </div>
              </div>
              <div class="goodsitembox_right">
                <p class="pointer" @click="deletegoods(index)">
                  <a-icon class="pointer" type="close-circle" />
                </p>
                <div class="bjq">
                  <p>数量：</p>
                  <p class="min pointer" @click="minnum(index)" :class="i.num == 1 ? 'active' : ''">一</p>
                  <a-input style="text-align: center; height:23px" placeholder="" v-model="i.num" />
                  <p class="plus pointer" @click="addnum(index)">➕</p>
                </div>
              </div>
            </div>
          </div>
          <div class="orderbox">
            <div class="orderitem">
              <p>优惠金额：</p>
              <a-input addon-before="➖" v-model="coupon_money" default-value="0.0" />
            </div>
          </div>

          <div class="orderbox">
            <div class="orderitem">
              <p>是否支付：</p>
              <a-select style="width: 100%" placeholder="请选择" @change="handleChangepay">
                <a-select-option v-for="i in payoption" :key="i.id">
                  {{ i.name }}
                </a-select-option>
              </a-select>
            </div>
          </div>

        </template>

        <div class="surebtn">
          <a-button type="primary" @click="makeorder" :loading="isBtnLoading" html-type="submit">确定下单</a-button>
        </div>

      </a-spin>
    </div>
    <a-modal width="760px" @ok="goodsvisible = false" :mask="false" v-model="goodsvisible">

      <a-spin :spinning="isLoading">
        <div class="modalbox ant-table">
          <div style="display: flex; align-items:center ">
            <a-input style="margin: 20px 0 ; width:70% " @input="goodschange" addon-before="商品名称 "
              v-model="goodsinput" />
            <a-button @click="refresh" type="primary" style="margin-left: 30px;">刷新库存</a-button>
          </div>
          <div class="typebox">
            <div v-for="(i, index) in bigtype" @click="changebigtype(i.category_id)" class="pointer"
              :class="bigtypecurrent == i.category_id ? 'active' : 'typebox_item'" :key="index">
              {{ i.name }}
            </div>
          </div>
          <div class="typebox " style="margin-top: 5px;">
            <div v-if="showsmall" v-for="(i, index) in smalltype" class="pointer"
              @click="changesmalltype(i.category_id)"
              :class="smalltypecurrent == i.category_id ? 'active' : 'typebox_item'" :key="index">
              {{ i.name }}
            </div>
          </div>
          <div style="background-color: #D8D8D8; padding:20px 10px;margin:5px 10px">
            <div class="newgoodsbox" @scroll="handleScroll">
              <div class="newgoodsbox_item pointer" @click="choose(i)" v-for="(i, index) in goodslist" :key="index">
                <img class="newgoodsbox_item_img" :src="i.goods_image" alt="">
                <div>
                  <div class="goodsname">{{ i.goods_name }}</div>
                  <div class="pricebox">
                    <span style="color: red">￥{{ i.goods_price_max }}</span>
                    <span>
                      <img src="../../../src/assets/kc.png" class="kucun" alt="">
                      <span>{{ i.stock_total }}</span>
                    </span>
                  </div>
                </div>
                <img class="choose_img" v-if="carlist.includes(i) == true" src="../../../src/assets/choose.png" alt="">
              </div>
            </div>
            <!-- <div class="pageclass">
              <a-pagination v-model="current" @change="changepage" :total="goodstotal" show-less-items />
            </div> -->
          </div>
        </div>
      </a-spin>
    </a-modal>
  </div>
</template>
<script>
import AMapLoader from '@amap/amap-jsapi-loader'
import * as Api from '@/api/order'
import axios from 'axios'
import * as shopApi from '@/api/store/user'
import throttle from 'lodash/throttle';
export default {
  data() {
    return {
      suggestions: [],
      showSuggestions: false,
      isLoading: false,
      goodslist: [],
      orderisLoading: false,
      bigtype: [],
      bigtypecurrent: 0,
      smalltypecurrent: 0,
      smalltype: [],
      coupon_money: 0,
      current: 1,
      isBtnLoading: false,
      shopListTreeData: [],
      goodsvisible: false,
      carlist: [],
      userInput: '', // 绑定的搜索关键字的的内容
      placeSearch: null,
      searchHere: null, // 根据搜索组件搜索到以后的地点信息
      lng: '',
      lat: '',
      address: '',
      buyer_remark: '',
      pre_times: '',
      detailaddress: '',
      phone: '',
      is_pay: null,
      customer: '',
      customerlist: [],
      customerphonelist: [],
      goodsinput: '',
      showsmall: false,
      goodstotal: 0,
      payoption: [{ name: '已支付', id: 1 }, { name: '未支付', id: 0 }],
      storecount: {},
      goodspage: 1
    }
  },
  computed: {
    allprice() {
      if (this.carlist.length === 0) {
        return 0
      } else {
        return this.carlist.reduce((price, ele) => {
          price += ele.price * ele.num
          return price
        }, 0)
      }
    }
  },
  mounted() {
    this.getshoplist()
    this.getcustomer()
    this.initMap()
  },
  methods: {
    //监听触底事件
    handleScroll: throttle(function (event) {
      const container = event.target; // 获取滚动容器
      const { scrollTop, clientHeight, scrollHeight } = container;
      // 判断是否触底
      if (scrollTop + clientHeight >= scrollHeight - 10) {
        this.goodspage++
        this.getgoodslist()
        console.log('触底了');

      }
    }, 200), // 200ms 内最多触发一次
    onInput() {
      if (this.userInput) {
        this.auto.search(this.userInput, (status, result) => {
          console.log('Search status:', status)
          console.log('Search result:', result)
          this.suggestions = result.tips;
          this.showSuggestions = true;
        })
      } else {
        this.suggestions = [];
        this.showSuggestions = false;
      }
    },

    onOk(date, dateString) {
      this.pre_times = dateString
    },
    // 选择或者取消选择商品
    choose(i) {
      // if (i.stock_total === 0) {
      //   this.$message.warning('暂无库存~')
      //   return false
      // }
      if (this.carlist.length > 0) {
        this.carlist.forEach(item => {
          if (i.goods_id === item.goods_id) {
            // this.carlist.splice(this.carlist.indexOf(i.goods_id), 1)
            this.$message.success('您已经添加过该商品~')
          }
        })
      } else {
        const obj = {
          image: i.goods_image,
          price: i.goods_price_max,
          name: i.goods_name,
          num: 1,
          goods_id: i.goods_id
        }
        this.carlist.push(obj)
      }

      if (this.carlist.length > 0) {
        console.log(this.carlist.some(item => {
          return item.goods_id === i.goods_id
        }))
        var a = this.carlist.some(item => {
          return item.goods_id === i.goods_id
        })
        if (!a) {
          const obj = {
            image: i.goods_image,
            price: i.goods_price_max,
            name: i.goods_name,
            num: 1,
            goods_id: i.goods_id
          }
          this.carlist.push(obj)
        }
      }
    },
    changepage(e) {
      this.goodspage = e
      shopApi.getgoods({ store_id: this.store_id, listRows: 6, category_id: this.category_id, page: this.goodspage, goodsName: this.goodsinput })
        .then(result => {
          this.goodslist = result.data.list.data
          this.goodstotal = result.data.list.total
        })
        .finally(result => {

        })
    },
    // 刷新库存
    refresh() {
      this.isLoading = true
      axios.post('https://test-ojjs.tt90.cc/index.php?s=/api/pospal/getPospalData', {
        store_id: this.store_id
      })
        .then(response => {
          this.isLoading = false
          this.getgoodslist()
        })
        .catch(error => {
          console.error('Error fetching data:', error);
        })

    },
    goodschange(e) {
      this.goodsinput = e.target.value
      shopApi.getgoods({ store_id: this.store_id, listRows: 12, category_id: this.category_id, page: 1, goodsName: this.goodsinput })
        .then(result => {
          this.goodslist = result.data.list.data
          this.goodstotal = result.data.list.total
        })
        .finally(result => {

        })
    },
    changesmalltype(id) {
      this.goodslist = []
      this.goodspage = 1
      this.showsmall = false
      this.smalltypecurrent = id
      this.category_id = id
      this.getgoodslist()
    },
    changebigtype(id) {
      this.showsmall = true
      this.bigtypecurrent = id
      this.smalltypecurrent = ''
      this.getsmalltype(id)
    },
    // 获取2级分类
    getsmalltype(id) {
      Api.smalltype({ uid: id, store_id: this.store_id }).then(res => {
        this.smalltype = res.data
      })
    },
    // 获取门店列表
    getshoplist() {
      shopApi.getshop({})
        .then(result => {
          result.data.map(item => {
            item.name = item.store_name
          })
          this.shopListTreeData = result.data
        })
        .finally(result => {

        })
    },
    //获取门店信息
    getStoreOrderCount(store_id) {
      shopApi.getStoreOrderCount({ store_id })
        .then(res => {
          this.storecount = res.data

        })
    },
    // 获取用户列表
    getcustomer() {
      shopApi.getuser({})
        .then(res => {
          this.customerlist = res.data
          this.customerphonelist = res.data.map(item => item.phone)
          // 对数组去重
          this.customerphonelist = Array.from(new Set(this.customerphonelist))
          this.customerlist = this.customerlist.filter((item, index, self) => {
            const firstOccurrence = self.findIndex((t) => t.long_info === item.long_info) === index
            return firstOccurrence
          })

        })
        .finally(result => {

        })
    },
    handleChangecustomer(e) {
      console.log(e, 'zzzzz')

      this.customerlist.map(item => {
        if (item.long_info === e) {
          console.log(item)
          this.customer = item.name
          this.phone = item.phone
          this.user_id = item.user_id
          this.detailaddress = item.address_detail
          this.userInput = item.address
          this.lng = item.longitude
          this.lat = item.latitude
        }
      })
    },
    handleChangephone(e) {
      this.phone = e

    },
    handleChangeaddress(e) {
      this.userInput = e

    },
    // 选择门店
    handleChangeshop(e) {
      this.goodslist = []
      this.carlist = []
      this.store_id = e
      this.getStoreOrderCount(e)
      this.getgoodslist()
      this.getbigtype(e)
    },
    //是否获取支付
    handleChangepay(e) {

      this.is_pay = e
    },
    // 获取一级分类
    getbigtype(id) {
      Api.bigtype({ store_id: id }).then(res => {
        this.bigtype = res.data
        this.bigtypecurrent = res.data[0].category_id
      })
    },
    // 获取当前门店商品列表
    getgoodslist() {
      shopApi.getgoods({ store_id: this.store_id, listRows: 12, category_id: this.category_id, page: this.goodspage, goodsName: this.goodsinput })
        .then(result => {
          this.goodslist = [...this.goodslist, ...result.data.list.data]
          this.goodstotal = result.data.list.total
        })
        .finally(result => {

        })
    },
    deletegoods(index) {
      this.carlist.splice(index, 1)
    },
    // 打开商品列表pop
    opengoodspop() {
      if (this.store_id) {
        this.goodsvisible = true
      } else {
        this.$message.warning('请先选择门店~')
      }
    },
    // 下单
    makeorder() {
      if (!this.lng || !this.lat) {
        this.$message.warning('请重新点击地图选点~')
        return false
      }
      if (!this.store_id) {
        this.$message.warning('请选择门店~')
        return false
      }
      if (this.is_pay == null) {
        this.$message.warning('请选择支付状态~')
        return false
      }
      if (this.carlist.length === 0) {
        this.$message.warning('请选择商品~')
        return false
      }
      if (!this.phone) {
        this.$message.warning('请输入手机号~')
        return false
      }
      this.orderisLoading = true
      this.isBtnLoading = true
      Api.makeorder({
        coupon_money: this.coupon_money,
        store_id: this.store_id,
        carlist: this.carlist,
        price: this.allprice,
        customer: this.customer,
        phone: this.phone,
        latitude: this.lat,
        pre_times: this.pre_times,
        longitude: this.lng,
        // merchant_remark: this.merchant_remark,
        is_pay: this.is_pay,
        buyer_remark: this.buyer_remark,
        address: this.userInput,
        address_detail: this.detailaddress
      }).then(async res => {
        this.orderisLoading = false
        this.store_id = ''
        this.carlist = ''
        this.allprice = ''
        this.customer = ''
        this.phone = ''
        this.lat = ''
        this.pre_times = ''
        this.lng = ''
        this.is_pay = ''
        this.buyer_remark = ''
        this.userInput = ''
        this.detailaddress = ''
        this.$message.success('创建成功~')

        this.isBtnLoading = false
        this.show = false
        this.$router.push({ path: '/order/list/all' })
      }).finally(res => {
        this.orderisLoading = false
      })

    },
    addnum(index) {
      this.carlist[index].num += 1
    },
    minnum(index) {
      if (this.carlist[index].num === 1) {
        this.carlist[index].num = 1
      } else {
        this.carlist[index].num -= 1
      }
    },
    initMap() {
      const that = this
      window._AMapSecurityConfig = {
        // securityJsCode: '7f9f1cdc2ff12403fd937336164e10cf'
        securityJsCode: '6bcce67e6ba128ea11f0ee0f59f02b09'
      }
      AMapLoader.load({
        // key: '7d1135f723e6c3892a1a271d219a33f2', // 申请好的Web端开发者Key，首次调用 load 时必填
        key: '86a1f68a89b18c1f6561e6d58816746a',
        version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.ToolBar', 'AMap.Scale', 'AMap.HawkEye', 'AMap.MapType',
          'AMap.Geolocation', 'AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.Geocoder'
        ] // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap) => {
        this.map = new AMap.Map('container', { // 设置地图容器id
          viewMode: '3D', // 是否为3D地图模式
          zoom: 17, // 初始化地图级别
          center: [114.819185, 34.814411] // 初始化地图中心点位置
        })
        // 地址逆解析插件
        this.geoCoder = new AMap.Geocoder({
          city: '010', // 城市设为北京，默认：“全国”
          radius: 1000 // 范围，默认：500
        })

        // 引入高德地图的空间绑定使用
        this.map.addControl(new AMap.Scale())
        this.map.addControl(new AMap.ToolBar())
        this.map.addControl(new AMap.HawkEye())
        this.map.addControl(new AMap.MapType())
        this.map.addControl(new AMap.Geolocation())
        this.auto = new AMap.AutoComplete({
          input: 'my-panel',
          output: 'hiddenElementId',
          panel: null // 不显示默认的下拉面板
        })
        //

        // this.placeSearch = new AMap.PlaceSearch({
        //   map: this.map,
        //   pageSize: 5,
        //   panel: 'my-panel'
        // })

        this.auto.on('select', this.zxcselect)// 绑定查询事件
        this.map.on('click', function (e) {
          that.lng = e.lnglat.getLng()
          that.lat = e.lnglat.getLat()
          that.toGeoCoder()

          that.biu()
        })
      }).catch(e => {
        console.log(e)
      })
    },
    // 逆解析地址
    toGeoCoder() {
      const lnglat = [this.lng, this.lat]
      this.geoCoder.getAddress(lnglat, (status, result) => {
        if (status === 'complete' && result.regeocode) {
          console.log(result.regeocode.formattedAddress)
          this.userInput = result.regeocode.formattedAddress
        }
      })
    },

    biu() {
      if (this.searchHere) {
        console.log(this.searchHere, 'hhh')
      }
    },
    zxcselect(e) {
      console.log(e, '我是地址')
      this.map.setZoom(10, true)
      this.searchHere = e.poi

      this.lng = this.searchHere.location.lng
      this.lat = this.searchHere.location.lat
      this.userInput = this.searchHere.name
    },
    selectSuggestion(suggestion) {
      this.map.setZoom(10, true)
      this.userInput = suggestion.name + suggestion.address
      this.searchHere = suggestion
      this.lng = this.searchHere.location.lng
      this.lat = this.searchHere.location.lat
      this.suggestions = [];
      this.showSuggestions = false;
      // 这里可以添加代码来处理选中的地址，比如在地图上显示该地点等
    },
  }
}
</script>

<style lang="less" scoped>
.makeorderbox {
  background-color: #fff;
  display: flex;
  padding-bottom: 50px;
}

.modalboxs {
  width: 60%;
}

.goodscontent {
  flex-wrap: wrap;
  display: flex;
  margin-left: 20%;
}

.goodsitembox {
  margin: 20px 10px;
  width: 250px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .goodsitembox_left {
    display: flex;
    width: 100px;

    img {
      width: 60px;
      height: 60px;

    }

    .goodsitembox_left_text {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      height: 60px;
    }
  }

  .goodsitembox_right {
    display: flex;
    flex-direction: column;
    height: 60px;
    justify-content: space-between;
    align-items: end;
  }
}

.bjq {
  display: flex;
  align-items: center;
  width: 130px;
  margin-left: 30px;

  >p {
    flex-shrink: 0;
  }

  .pointer {
    cursor: pointer;
  }

  .min {
    border: 1px solid #d9d9d9;
    padding: 0px 5px;
  }

  .active {
    background-color: #dddcdc;
  }

  .plus {
    border: 1px solid #d9d9d9;
    padding: 0px 5px;
  }
}

.typebox {
  background-color: #5FA4E7;
  border-radius: 20px;
  width: 100%;
  display: flex;
  align-items: center;
  color: #fff;
  overflow-x: auto;

  .active {
    background-color: #387FD7;
    padding: 15px 30px;
    flex-shrink: 0;

  }

  .typebox_item {
    padding: 15px 30px;
    flex-shrink: 0;

  }
}

.heji {
  align-items: center;
  display: flex;
  justify-content: flex-end;
  width: 300px;

}

.newgoodsbox {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  overflow-y: auto;
  max-height: 400px;

  .newgoodsbox_item {
    position: relative;
    width: 200px;
    border-radius: 10px;
    margin: 5px 10px;
    background-color: #fff;
    padding: 15px;
    display: flex;
    align-items: center;
    justify-content: center;



    .newgoodsbox_item_img {
      width: 50px;
      height: 50px;
      margin-bottom: 10px;
      margin-right: 10px;
    }

    .pricebox {
      margin: 10px 0;
      padding-right: 10px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .kucun {
      width: 20px;
      height: 20px
    }

    .choose_img {
      width: 20px;
      height: 20px;
      position: absolute;
      top: 10px;
      right: 20px;
    }
  }

  .goodsname {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 130px;
  }
}



.surebtn {
  display: flex;
  width: 575px;
  justify-content: flex-end;
}

.orderboxaddress {
  display: flex;
  align-items: center;
  margin-left: 20%;

  .orderitem {
    width: 100%;
    margin: 15px 5px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: relative;

    .autocomplete-results {
      /* 自定义下拉列表样式 */
      position: absolute;
      border: 1px solid #ccc;
      background: white;
      z-index: 10000;
      top: 35px;
      left: 70px;
      width: 540px;
    }

    .autocomplete-results div {
      padding: 5px;
      cursor: pointer;
    }

    .autocomplete-results div:hover {
      background: #f0f0f0;
    }

    >p {
      flex-shrink: 0;
      text-align: right;
      width: 70px;

    }
  }
}

.orderbox {
  margin-left: 20%;
  display: flex;
  align-items: center;
  position: relative;

  #container {
    padding: 0px;
    margin-left: 70px;
    width: 100%;
    height: 300px;
  }

  .orderitem {
    width: 100%;
    margin: 15px 5px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    >p {
      flex-shrink: 0;
      text-align: right;
      width: 70px;

    }
  }

}
</style>
